package com.spring.tools;

import java.io.File;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import net.sf.json.JSONArray;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;
import com.spera.aliyunContent.AliyunContent;
import com.spera.aliyunUtil.CreateOSSClient;
import com.spera.aliyunUtil.SperaOSSUtil;
import com.spera.exception.MyException;
import com.spera.genutil.tools;
import com.spring.appservice.web.service.MainShowService;
import com.spring.comment.web.dao.CommentMapper;
import com.spring.common.web.dao.CommonApiMapper;
import com.spring.security.core.util.ApplicationUtils;
import com.spring.security.core.util.UDate;
import com.spring.security.web.dao.JedisCache;
import com.spring.security.web.model.BaseResult;
import com.sso.api.web.model.TracelogboWithBLOBs;

import org.apache.commons.lang.StringUtils;

@Service
public class MyTools {
	/**
	 * page_index转换rows
	 * @param page_size
	 * @param page_index
	 * @param skip
	 * @param rows
	 * @return
	 */
	@Resource private JedisCache jedisCache;
	
	@Resource private CommonApiMapper commonApiMapper;	

	public static HashMap<String,Object> pageIndexToSkip(String page_size,String page_index,String skip,String rows){
		
		int pagesize=20;
		int pageindex=1;
		int skipint=0;
		int rowsint=20;
		
		if(page_size!=null&&page_index!=null){
			
			 pagesize=Integer.parseInt(page_size);
			 pageindex=Integer.parseInt(page_index);
			
			skipint=pagesize*(pageindex-1);
			rowsint=pagesize;
			
		}else if(skip!=null&&rows!=null){
			
			 skipint=Integer.parseInt(skip);
			 rowsint=Integer.parseInt(rows);
			
		}
		
		
		HashMap<String,Object> hm=new HashMap<String,Object>();
		hm.put("skip", skipint);
		hm.put("rows", rowsint);
		
		return hm;
	}
	
	
public static HashMap<String,Object> pageIndexToSkipSearchAll(String page_size,String page_index,String skip,String rows){
		HashMap<String,Object> hm=new HashMap<String,Object>();
	
		int pagesize=20;
		int pageindex=1;
		int skipint=0;
		int rowsint=20;
		
		String searchAll=null;
		
		if(page_size!=null&&page_index!=null){
			
			 pagesize=Integer.parseInt(page_size);
			 pageindex=Integer.parseInt(page_index);
			
			skipint=pagesize*(pageindex-1);
			rowsint=pagesize;
			
		}else if(skip!=null&&rows!=null){
			
			 skipint=Integer.parseInt(skip);
			 rowsint=Integer.parseInt(rows);
			
		}else{
			searchAll="1";
			hm.put("searchAll", searchAll);
			return hm;
		}
		
		hm.put("skip", skipint);
		hm.put("rows", rowsint);
		
		return hm;
	}

public static HashMap<String,Object> pageIndexToSkipSearchAllLimit(String page_size,String page_index,String skip,String rows){

	int pagesize=20;
	int pageindex=1;
	int skipint=0;
	int rowsint=100000;
	
	if(page_size!=null&&page_index!=null&&!page_size.equals("")&&!page_index.equals("")){
		
		 pagesize=Integer.parseInt(page_size);
		 pageindex=Integer.parseInt(page_index);
		
		skipint=pagesize*(pageindex-1);
		rowsint=pagesize;
		
	}else if(skip!=null&&rows!=null){
		
		 skipint=Integer.parseInt(skip);
		 rowsint=Integer.parseInt(rows);
		
	}
	
	
	HashMap<String,Object> hm=new HashMap<String,Object>();
	hm.put("skip", skipint);
	hm.put("rows", rowsint);
	
	return hm;
}
	
	
	
	public static HashMap<String,Object> checkIsNotNull(String... parameter){
		HashMap<String,Object> hm = null;
		for(int i=0;i<parameter.length;i++){
			if(!ApplicationUtils.isNotNull(parameter[i])){
				hm=new HashMap<String,Object>();
				hm.put(ApplicationUtils.STATUS, "0");
				hm.put(ApplicationUtils.MSG, "请输入必要的参数");
				return hm;
			}
		}
		return hm;
	}

	public static BaseResult checkIsNotNullBR(String... parameter) {

		BaseResult br = null;
		for (int i = 0; i < parameter.length; i++) {
			if (!ApplicationUtils.isNotNull(parameter[i])) {
				return new BaseResult("0", "请输入必要参数");
			}
		}
		return br;
	}
	
	
	public static String timestampToString(String timestamp) throws Exception {
		
		Timestamp ts = new Timestamp(Integer.parseInt(timestamp)*1000);
		
		DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String time = null;

		time = sdf.format(ts);

		return time;
	}

public static List parseJsonToList(String jsonstr,Class objectClass){
	

	JSONArray json = JSONArray.fromObject(objectClass);

	List list= JSONArray.toList(json, objectClass);
	
	return list;
}

	// 宝宝树附件上传

	public static HashMap<String, Object> commitFile(MultipartFile file) throws Exception {

		HashMap<String, Object> m = new HashMap<String, Object>();
		try {

			if (!file.isEmpty()) {
//				String fileName = file.getOriginalFilename();
//				String fileType = tools.getFileType(fileName);
				
				String fileType = tools.getFileType(file.getName());
				if(!ApplicationUtils.isNotNull(fileType)){
					m.put(ApplicationUtils.STATUS, "0");
					m.put(ApplicationUtils.MSG, "未知附件类型");
					return m;
				}
				
				
				if(!tools.checkFileType(fileType,"jpg","jpeg","bmp","png")){
					m.put(ApplicationUtils.STATUS, "0");
					m.put(ApplicationUtils.MSG, "附件类型不允许");
					return m;
				}

				String newfilename = "bt_" + ApplicationUtils.randomUUID()+ "." + fileType;

				Integer fileSize = 0;
				fileSize = (int) file.getSize() / 1024;
				if (fileSize <= 102400) {
					String filePath = SperaOSSUtil.springFileUpOss(AliyunContent.fileBucket,"babyTreeRecord/" + UDate.getDate() + "/"+ newfilename, file);
					m.put(ApplicationUtils.STATUS, "1");
					m.put(ApplicationUtils.MSG, "上传成功");
					m.put("filePath", filePath);
					m.put("osskey", "babyTreeRecord/" + UDate.getDate() + "/"+ newfilename);
					
					
					return m;					
				} else {
					m.put(ApplicationUtils.STATUS, "0");
					m.put(ApplicationUtils.MSG, "上传的文件太大，文件大小不能超过5M");
					return m;
				}
			} else {
				m.put(ApplicationUtils.STATUS, "0");
				m.put(ApplicationUtils.MSG, "请选择上传的文件");
			}

		} catch (Exception e) {
			m.put(ApplicationUtils.STATUS, "0");
			m.put(ApplicationUtils.MSG, "系统异常");
			e.printStackTrace();
		}

		return m;

	}
	
	
	public  HashMap<String, Object> commitFile2(String folder,MultipartFile file) throws Exception {

		HashMap<String, Object> m = new HashMap<String, Object>();


			if (!file.isEmpty()) {
				
				System.out.println(tools.getFileType(file.getOriginalFilename()));
				System.out.println("-------------");
				
				String fileType = tools.getFileType(file.getOriginalFilename());
				
				System.out.println(tools.getFileType(file.getName()));
				System.out.println("-------------");
				
/*				if(!ApplicationUtils.isNotNull(fileType)){
					m.put(ApplicationUtils.STATUS, "0");
					m.put(ApplicationUtils.MSG, "未知附件类型");
					return m;
				}
				*/
				
//				if(!tools.checkFileType(fileType,"jpg","jpeg","bmp","png")){
//					m.put(ApplicationUtils.STATUS, "0");
//					m.put(ApplicationUtils.MSG, "附件类型不允许");
//					return m;
//				}
				String newfilename="";
				if(fileType!=null&&!fileType.equals("")){
				newfilename = "cm_" + ApplicationUtils.randomUUID()+ "." + fileType;
				}else{
				 newfilename = "cm_" + ApplicationUtils.randomUUID();	
				}
				
				
				Integer fileSize = 0;
				fileSize = (int) file.getSize() / 1024;
/*				if (fileSize <= 102400) {*/
					String filePath = SperaOSSUtil.springFileUpOss(AliyunContent.fileBucket,"folder"+"/" + UDate.getDate() + "/"+ newfilename, file);								
					
					String fileID=ApplicationUtils.randomUUID();
					
					HashMap hmp=new HashMap();
					hmp.put("fileID", fileID);
					hmp.put("url", filePath);
					hmp.put("osskey", folder+"/" + UDate.getDate() + "/"+ newfilename);
					hmp.put("bucket", AliyunContent.fileBucket);
					
					
					//babyTreeMapper.createFile(hmp);
					int effect=commonApiMapper.createFile(hmp);
					if(effect<1){
						m.put(ApplicationUtils.STATUS, "0");
						m.put(ApplicationUtils.MSG, "上传失败");
					}
				
					m.put(ApplicationUtils.STATUS, "1");
					m.put(ApplicationUtils.MSG, "上传成功");
					m.put("fileID", fileID);
					m.put("url", filePath);
							
					return m;					
/*				} else {
					m.put(ApplicationUtils.STATUS, "0");
					m.put(ApplicationUtils.MSG, "上传的文件太大，文件大小不能超过5M");
					return m;
				}*/
			} else {
				m.put(ApplicationUtils.STATUS, "0");
				m.put(ApplicationUtils.MSG, "请选择上传的文件");
			}



		return m;

	}
	
	
	
	public  HashMap<String, Object> checkCaptcha(String phone,String captcha) throws Exception{
		HashMap<String, Object> m=new HashMap<String, Object>();
		
		if (!ApplicationUtils.isNotNull(captcha)) {
			m.put(ApplicationUtils.STATUS, "0");
			m.put(ApplicationUtils.MSG, "请输入短信验证码");
			return m;
		}
		
		if(!jedisCache.exists(phone)){
			m.put(ApplicationUtils.STATUS, "0");
			m.put(ApplicationUtils.MSG, "验证码已过期，请重新发送");
			return m;
		}
		
		String val_num = jedisCache.get(phone);
		if(!captcha.equals(val_num)){
			m.put(ApplicationUtils.STATUS, "0");
			m.put(ApplicationUtils.MSG, "验证码不正确");
			return m;
		}		
		return null;
	}
	public static String ObjectToString(Object o){
		String r=String.valueOf(o);
		if(r.equals("")||r.equals("null")){
			r=null;
		}
		return r;
	}	

	public static BaseResult checkResult(int... effect) throws Exception{

		for(int eff:effect){
			if(eff==0){
				return new BaseResult("0","失败");		
			}
		}				
		return new BaseResult("1","成功");	
	}
	
	public static void checkEffect(int... effect) throws Exception{
		for(int eff:effect){
			if(eff==0){
				throw new MyException("更新插入失败");
			}
		}					
	}
	
	
    public static String springFileUpOss(String bucketName, String key, MultipartFile file)
            throws Exception {
    	OSSClient client = CreateOSSClient.getInstance().getOSSClient();
        ObjectMetadata objectMeta = new ObjectMetadata();
        objectMeta.setContentLength(file.getSize());
        // 可以在metadata中标记文件类型
       // objectMeta.setContentType("image/jpeg");
        client.putObject(bucketName, key, file.getInputStream(), objectMeta);
        return "http://" + bucketName + ".oss-cn-hangzhou.aliyuncs.com/" + key;
    }
	
	public static BaseResult analyseError(Exception e){		
		if(e instanceof MyException){	
			MyException myException=(MyException)e;
			String msg=myException.getMessage();
			String status=myException.getStatus();
			
			return new BaseResult(status,msg);
		}else{
			e.printStackTrace();
			return new BaseResult("0","系统异常");
		}	
	}
	
	public static TracelogboWithBLOBs getLog(JedisCache jedisCache,String token,HttpServletRequest request){
		TracelogboWithBLOBs tl = getLogByRequest(request);
		
		Map<String, String> user=jedisCache.hgetAll(token);
		String userID=user.get("user_id");
		String userName=user.get("user_name");
		String deviceCategory=user.get("deviceCategory");
		if(deviceCategory!=null){
			tl.setDevicecategory(Integer.parseInt(deviceCategory));
		}
		tl.setInitialoperatorid(userID);
		tl.setInitialoperatorname(userName);
		return tl;
	}

	public static TracelogboWithBLOBs getLogByRequest(HttpServletRequest request){
		
		String url = request.getRequestURL()+"";	
		String ipaddress = getIpAddr(request);
		
		TracelogboWithBLOBs tl=new TracelogboWithBLOBs();
		tl.setIpaddress(ipaddress);
		tl.setUrl(url);
		return tl;
	}

	public static String getIpAddr(HttpServletRequest request) {
		 String ip = request.getHeader("x-forwarded-for");
		 if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
		  ip = request.getHeader("Proxy-Client-IP");
		 }
		 if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
		  ip = request.getHeader("WL-Proxy-Client-IP");
		 }
		 if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
		  ip = request.getRemoteAddr();
		 }
		 if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
		  ip = request.getHeader("http_client_ip");
		 }
		 if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
		  ip = request.getHeader("HTTP_X_FORWARDED_FOR");
		 }
		 // 如果是多级代理，那么取第一个ip为客户ip
		 if (ip != null && ip.indexOf(",") != -1) {
		  ip = ip.substring(ip.lastIndexOf(",") + 1, ip.length()).trim();
		 }
		 return ip;
	}
	
	@SuppressWarnings("rawtypes")
	public static String getChangeByMap(Map<String, Object> m,String type) {
		type=(type==null?"修改":null);
		
		String change=type+":";		
		Set set = m.entrySet();
		Iterator iterator = set.iterator();
		while (iterator.hasNext()) {
			Map.Entry mapentry = (Map.Entry) iterator.next();
			if(mapentry.getValue()!=null&&!mapentry.getValue().equals("")){
				change=change+mapentry.getKey()+"["+mapentry.getValue()+"],";
			}			
		}
		return change;
	}	

	public static String getChangeByMap(HashMap<String, Object> hm,String type) {
		Map<String, Object> m = hm;
		return getChangeByMap(m,type);
	}
}
